import React, { useCallback } from 'react';
import clsx from 'clsx';
import Link from '@docusaurus/Link';
import Heading from '@theme/Heading';
import styles from './styles.module.css';

import { Tags, TagList, type TagType } from '@site/src/data/tags';
import { sortBy } from '@site/src/utils/jsUtils';
import { MessageProvider, useMessageHelpers } from '@site/src/components/Message/MessageProvider';

interface Community {
  communityId: string;
  communityName: string;
  url: string;
  pic: string;
  profile: string;
  labelsArray: TagType[];
  focus: boolean;
  communityCode: string;
  showFocusButton: boolean;
}

interface ShowcaseCardProps {
  item: Community;
  onCommunityJoin: (communityCode: string) => Promise<boolean>;
  onJoinSuccess?: () => void;
}

// 生成一致的颜色
const generateTagColor = (tag: string): string => {
  let hash = 0;
  for (let i = 0; i < tag.length; i++) {
    hash = tag.charCodeAt(i) + ((hash << 5) - hash);
  }
  const hue = hash % 360;
  return `hsl(${hue}, 70%, 60%)`;
};

function TagItem({ tag }: { tag: string }) {
  const color = generateTagColor(tag);
  const key = `${tag}-${color}`;

  return (
    <li className={styles.tag} title={tag} key={key}>
      <span className={styles.textLabel}>{tag}</span>
      <span
        className={styles.colorLabel}
        style={{ backgroundColor: color }}
      />
    </li>
  );
}

function ShowcaseCardTag({ tags }: { tags: TagType[] }) {
  const tagObjects = tags.map((tag) => ({ tag, ...Tags[tag] }));
  const tagObjectsSorted = sortBy(tagObjects, (tagObject) => TagList.indexOf(tagObject.tag));

  return (
    <>
      {tagObjectsSorted.map((tagObject) => (
        <TagItem key={tagObject.tag} {...tagObject} />
      ))}
    </>
  );
}

function ShowcaseCardInner({ item, onCommunityJoin, onJoinSuccess }: ShowcaseCardProps) {
  const [isFollowing, setIsFollowing] = React.useState(false);
  const { success, error } = useMessageHelpers();

  const {
    communityId,
    communityName,
    communityCode,
    url,
    pic,
    profile,
    labelsArray,
    focus,
    showFocusButton
  } = item;

  const handleJoinClick = useCallback(async () => {
    if (typeof window !== 'undefined' && window._oafs) {
      window._oafs.action(`${communityName}-关注`, {
        id: communityId,
        code: communityCode,
      });
    }

    try {
      setIsFollowing(true);

      const result = await onCommunityJoin(communityCode);

      if (!result) {
        return;
      }

      onJoinSuccess?.();

      success('关注成功！');
    }
    catch (err) {
      const errorObj = err as Error;
      console.error('Join community error:', errorObj);
      error(errorObj?.message || '网络错误，请检查网络连接后重试');
    }

    setIsFollowing(false);
  }, [onCommunityJoin, communityCode, onJoinSuccess, success, error]);

  const handleLinkClick = () => {
    if (typeof window !== 'undefined' && window._oafs) {
      window._oafs.action(`${communityName}-跳转`, {
        id: communityId,
        code: communityCode,
      });
    }
  }

  return (
    <li key={communityId} className="card shadow--md">
      <div className={clsx('card__image', styles.showcaseCardImage)}>
        <img src={pic} alt={communityName} />
      </div>
      <div className="card__body">
        <div className={clsx(styles.showcaseCardHeader)}>
          <Heading as="h4" className={styles.showcaseCardTitle}>
            <Link href={url} className={styles.showcaseCardLink} onClick={handleLinkClick}>
              {communityName}
            </Link>
          </Heading>
          {showFocusButton && (
            <button
              type="button"
              className={clsx(styles.followBtn, {
                [styles.following]: focus,
                [styles.loading]: isFollowing
              })}
              onClick={handleJoinClick}
              disabled={isFollowing || focus}
            >
              {isFollowing ? '处理中...' : focus ? '已关注' : '关注'}
            </button>
          )}

        </div>
        <p className={styles.showcaseCardBody}>{profile}</p>
      </div>
      <ul className={clsx('card__footer', styles.cardFooter)}>
        <ShowcaseCardTag tags={labelsArray} />
      </ul>
    </li>
  );
}

function ShowcaseCard({ item, onCommunityJoin, onJoinSuccess }: ShowcaseCardProps) {
  return (
    <MessageProvider>
      <ShowcaseCardInner
        item={item}
        onCommunityJoin={onCommunityJoin}
        onJoinSuccess={onJoinSuccess}
      />
    </MessageProvider>
  );
}

export default React.memo(ShowcaseCard);
